package oauth.service.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

import oauth.repository.mapperadd.SpringSecurityMapper;
import oauth.repository.modelAdd.SysUserRoleRescsDTO;

public class FilterInvocationSecurityMetadataSourceCust implements FilterInvocationSecurityMetadataSource
{
	@Autowired
	private SpringSecurityMapper springSecurityMapper;
	private LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> resourceMap = null;

	// @PostConstruct
	DefaultFilterInvocationSecurityMetadataSource loadResourceDefine()
	{
		List<SysUserRoleRescsDTO> sysRoleRescs = springSecurityMapper.selectAllURL_Role();
		resourceMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();

		for (SysUserRoleRescsDTO srr : sysRoleRescs)
		{
			ConfigAttribute ca = new SecurityConfig(srr.getRoleName());// ROLE_XXXX
			RequestMatcher url = new AntPathRequestMatcher(srr.getRescString());// URL
			/*
			 * 将权限增加到权限集合中
			 * index.jsp ROLE_AdMIN
			 * index.jsp ROLE_MAN
			 * map<index.jsp, [ROLE_AdMIN,ROLE_MAN]>
			 */
			if (resourceMap.containsKey(url))
			{
				Collection<ConfigAttribute> value = resourceMap.get(url);
				value.add(ca);
				resourceMap.put(url, value);
			}
			else
			{
				// 没有URL就新建key
				Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
				atts.add(ca);
				resourceMap.put(url, atts);
			}
		}
		return new DefaultFilterInvocationSecurityMetadataSource(resourceMap);
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes()
	{
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
	{
		return loadResourceDefine().getAttributes(object);
	}

	@Override
	public boolean supports(Class<?> arg0)
	{
		return true;
	}

}
